/**
 * @file 工单操作-服务完成审核
 * @author songweidong
 * @date 2019-07-10 16:20:25
 */
layui.define(['layer', 'upload', 'form', 'list_modify_common', '$http','previewer'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let opCommonUtils = layui.list_modify_common;
    let $http = layui.$http;
    let layer = layui.layer;
    let upload = layui.upload;
    var previewer = layui.previewer;
    let timestamp = new Date().getTime();
    let newServiceItemList = [];

    var GET_TIERED_TOTAL_PRICE='/work/modify/serviceitem/tieredtotalprice.action';

    function submit(data) {

        let url = "/work/modify/save/serviceCompleteReview.action";

        let params = _normalizeSubmitParams(data);
        data.field.auditReason = params.auditReason;

        if (data.field.serviceCompleteReviewStatus === "3" && data.field.auditReason.length === 0) {
            layer.msg("失败缘由不能为空");
            return;
        }

        data.field.serviceItemVOList = newServiceItemList;

        $http.lockSave(url, data.field, data.elem).then(function () {
            layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                opCommonUtils.goOperateHome();
            });
        }, function (msg) {
            layer.msg(msg);
        });
    }

    /**
     * 验证表单
     */
    function initFormVerify () {
        form.verify({
            // 必填校验
            otherReq: function(value,item){
                var $ = layui.$;
                var verifyName=$(item).attr('name')
                    , verifyType=$(item).attr('type')
                    ,formElem=$(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                    ,verifyElem=formElem.find('input[name='+verifyName+']')//获取需要校验的元素
                    ,isTrue= verifyElem.is(':checked')//是否命中校验
                    ,focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
                if(!isTrue || !value){
                    //定位焦点
                    focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
                    //对非输入框设置焦点
                    focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
                        focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
                    }).focus();
                    return '必填项不能为空';
                }
            }
        })
    }

    /**
     * 失败原因处理
     * @param data
     */
    function _normalizeSubmitParams (dataObj) {
        var params = {
            auditReason: []
        };

        $(dataObj.form).serializeArray().forEach(({ name, value }) => {
            if (name === 'auditReason') {
                params.auditReason.push({
                    text: _getInputTitleByNameAndValue(name, value),
                    value: value
                });
                return;
            }
            params[name] = value;
        });

        return params;
    }

    function _getInputTitleByNameAndValue (name, value) {
        return $('input[name="' + name + '"][value="' + value + '"]').attr('title');
    }

    /**
     * 初始化页面
     */
    function initPage() {
        // 初始化表单
        initFormVerify();
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        //输入框正在输入时
        $("input[name='internalSettlementPrice']").on('input',function(){
            var $this = $(this);
            var value = $this.val()
                .replace(/\-{1,}/g,'')
                .replace(/[^\d.-]/g, '')
                .replace(/^\./g, '')
                .replace(/\.{2,}/g, '.')
                .replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
                .replace(/^(\d+)\.(\d\d).*$/, '$1.$2');
            // 内部价不能超过10W
            if (value > 100000){
                value = 100000;
            }
            $this.val(value);
        });

        //输入框失去焦点时
        $("input[name='internalSettlementPrice']").on('blur',function(){
            let $this = $(this);
            let price = opCommonUtils.accMul($this.val(), 100);
            let number = $this.parent().parent().find('.item-number').text();
            // 阶梯总价
            let tempTotalPrice;

            let servItemId = $this.attr("data-service-item-id");
            let serviceItem = reviewVO.orderServiceItemList.find((item) => (item.servItemId == servItemId));
            if (serviceItem.itemPrice == 0 && serviceItem.number > 1) {
                var params = {
                    orderId: $("input[name='orderId']").val(),
                    itemId: Number.parseInt(curr.servItemId),
                    number: Number.parseInt(curr.number),
                    detailList: serviceItem.itemDetailList
                };
                $.ajax({
                    url: GET_TIERED_TOTAL_PRICE,
                    type: 'post',
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(params),
                    success: function (response) {
                        if (response.status === 200) {
                            tempTotalPrice = response.data;
                        } else {
                            layer.msg("请求阶梯价失败" + response.message);
                        }
                    },
                    error: function () {
                        layer.msg('网络错误，请重试');
                    }
                })
            } else {
                tempTotalPrice = opCommonUtils.accMul(price, number);
            }
            $this.parent().prev().prev().text(tempTotalPrice);

            let item = newServiceItemList.find((item) => (item.servItemId == servItemId));

            if (item){
                item.internalSettlementPrice = price;
                item.internalTotalPrice = tempTotalPrice;
            } else {
                newServiceItemList.push({
                    servItemId: serviceItem.servItemId,
                    servItemName: serviceItem.servItemName,
                    oldInternalSettlementPrice: serviceItem.internalSettlementPrice,
                    internalSettlementPrice: price,
                    internalTotalPrice: tempTotalPrice
                });
            }

            let totalPrice = 0;
            $("input[name='internalSettlementPrice']").each(function () {
                /*let itemPrice = $(this).val();
                let itemNumber = $(this).parent().parent().find('.item-number').text();
                let itemTotalPrice = opCommonUtils.accMul(itemPrice, itemNumber);*/
                let itemTotalPrice = $(this).parent().prev().prev().text();
                totalPrice = opCommonUtils.accAdd(totalPrice, itemTotalPrice);
            });
            // 设置工单价格总价
            $("#internalTotalPrice").text(totalPrice/100);
        });

        // 失败原因显示
        form.on('radio(reviewResult)', function (data) {
            if (data.value === "3") {
                $('#fail-reason').show();
            } else {
                $('#fail-reason').hide();
            }
            // 切换清空勾选项
            $("input[name='auditReason']").prop('checked',false);
            form.render("checkbox");
        });

        // 将失败缘由备注拼接到审核备注中。
        form.on('checkbox(auditReason)', function (data) {
            if (data.elem.checked) {
                let $input = $(data.elem);
                let attr = $input.attr('content');
                let $content = $('#content');
                $content.val($content.val() + attr);
            }
        });

        // 保存
        form.on('submit()', function (data) {
            submit(data);
            return false
        });
    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

    }

    // 初始化
    init();
    exports('oms_work_modify_servicecompletereview');
});
